/* ***** BEGIN LICENSE BLOCK *****
 *   Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is sudoku.
 *
 * The Initial Developer of the Original Code is
 * Petr Blahoš.
 * Portions created by the Initial Developer are Copyright (C) 2008
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 * 
 * ***** END LICENSE BLOCK ***** */

Components.utils.import("resource://sudoku/griddb.jsm");

var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
var sudokuPrefs = prefService.getBranch("extensions.sudoku.");

function LOG(msg) {
	var consoleService = Components.classes["@mozilla.org/consoleservice;1"]
			.getService(Components.interfaces.nsIConsoleService);
	consoleService.logStringMessage(msg);
}

var treeView = {
	init: function() {
		this.strings = document.getElementById("main-strings");
		this.tree = document.getElementById('my-tree');
		this.onRating(sudokuPrefs.getIntPref("sidebar.view"));
		this.browser = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                   .getInterface(Components.interfaces.nsIWebNavigation)
                   .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                   .rootTreeItem
                   .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                   .getInterface(Components.interfaces.nsIDOMWindow).gBrowser;
	},
	getGrid: function(row) {
		var s1 = griddb.conn.createStatement(this.grid_q);
		s1.bindInt32Parameter(0, row);
		if (s1.executeStep()) {
			return new GRID(
				s1.getInt32(0),
				s1.getInt32(1),
				s1.getString(2),
				s1.getInt32(3),
				s1.getInt32(4),
				s1.getInt32(5),
				s1.getInt32(6),
				s1.getInt32(7));
		}
		return new GRID(null, null, gid, 50, 0, 0, 0, 0);
	},
	get rowCount() {
		var s1 = griddb.conn.createStatement(this.count_q);
		var count = 0;
		if (s1.executeStep()) {
			count = s1.getInt32(0);
		}
		return count;
	},
	getCellText: function(row,column) {
		if ("play"==column.id) {
			return ">>";
		}
		grid = this.getGrid(row);
		if ("id"==column.id) {
			return grid.id;
		}
		if ("best"==column.id) {
			return grid.get_best_time();
		}
		else return "" + grid.rating;
	},
	setTree: function(treebox){ this.treebox = treebox; },
	isContainer: function(row){ return false; },
	isSeparator: function(row){ return false; },
	isSorted: function(){ return false; },
	getLevel: function(row){ return 0; },
	getImageSrc: function(row,col){ return null; },
	getRowProperties: function(row,props){},
	getCellProperties: function(row,col,props){},
	getColumnProperties: function(colid,col,props){},

	onselect: function(ev) {
		var grid = griddb.get_grid_by_pos(this.tree.currentIndex);
	},
	onclick: function(tree, ev) {
		var tbo = tree.treeBoxObject;
		var row = { }, col = { }, obj = { };
		tbo.getCellAt(ev.clientX, ev.clientY, row, col, obj);
		if (row.value<0 || row.value>this.rowCount) {
			return ;
		}
		if ("play"!=col.value.id) {
			return ;
		}
		this.openGrid(this.getGrid(row.value));
	},
	onkey: function(ev) {
		if (KeyEvent.DOM_VK_RETURN==ev.keyCode) {
			this.openGrid(griddb.get_grid_by_pos(this.tree.currentIndex));
			//if (this.treeBox) {
			//	this.treeBox.invalidate();
			//}
		}
	},
	openGrid: function(grid) {
		var uri = "chrome://sudoku/content/grid.xul?id="+grid.id;
		this.browser.selectedTab = this.browser.addTab(uri);
		/*for (var i = 0;i<this.browser.tabContainer.childNodes.length;i++) {
			var b = this.browser.getBrowserAtIndex(i);
			LOG("TAB: " + b.currentURI.spec);
			if (0==b.currentURI.spec.indexOf("chrome://sudoku/content/grid.xul")) {
				c.currentURI = 
			}
		}*/
	},
	onRating: function(rating) {
		var tail = "";
		switch(rating) {
		case 0:
			treeView.count_q = "SELECT COUNT(*) FROM grids WHERE rating<0";
			treeView.grid_q = "SELECT id, gid, grid, rating, date, best, sum, count FROM grids WHERE rating<0 ORDER BY best LIMIT 1 OFFSET ?1";
			tail = this.strings.getString("gridsidebar.unrated");
			break;
		case 1:
			treeView.count_q = "SELECT COUNT(*) FROM grids WHERE rating>=0 AND rating<50";
			treeView.grid_q = "SELECT id, gid, grid, rating, date, best, sum, count FROM grids WHERE rating>=0 AND rating<50 ORDER BY best LIMIT 1 OFFSET ?1";
			tail = this.strings.getString("gridsidebar.easy");
			break;
		case 2:
			treeView.count_q = "SELECT COUNT(*) FROM grids WHERE rating>=50 AND rating<70";
			treeView.grid_q = "SELECT id, gid, grid, rating, date, best, sum, count FROM grids WHERE rating>=50 AND rating<70 ORDER BY best LIMIT 1 OFFSET ?1";
			tail = this.strings.getString("gridsidebar.medium");
			break;
		default:
			rating = 3;
			treeView.count_q = "SELECT COUNT(*) FROM grids WHERE rating>=70";
			treeView.grid_q = "SELECT id, gid, grid, rating, date, best, sum, count FROM grids WHERE rating>=70 ORDER BY best LIMIT 1 OFFSET ?1";
			tail = this.strings.getString("gridsidebar.hard");
			break;
		}
		treeView.tree.view = this;
		sudokuPrefs.setIntPref("sidebar.view", rating);
		document.getElementById('viewButton').label = this.strings.getString("gridsidebar.view") + " " + tail;

	},
	treetip_showing: function(ev) {
		var tbo = treeView.tree.treeBoxObject;
		var row = { }, col = { }, obj = { };
		tbo.getCellAt(ev.clientX, ev.clientY, row, col, obj);
		if (row.value<0 || row.value>treeView.rowCount) {
			return false;
		}
		var grid = this.getGrid(row.value);
		for (var i = 0;i<grid.grid.length;i++) {
			var c = grid.grid.charAt(i);
			var el = document.getElementById("g" + i);
			if ('0'==c) {
				c = '';
				el.style.font.weight = "bold";
			}
			el.value = c;
		}

		var out = "";
		var temp;

		document.getElementById("tiptext1").value = "";
		document.getElementById("tiptext2").value = "";
		document.getElementById("tiptext3").value = "";
		document.getElementById("tiptext4").value = "";
		document.getElementById("tiptext5").value = "";
		try {
			temp = "";
			if (grid.is_easy()) {
				temp = this.strings.getString("gridsidebar.easy");
			} else if (grid.is_medium()) {
				temp = this.strings.getString("gridsidebar.medium");
			} else if (grid.is_hard()) {
				temp = this.strings.getString("gridsidebar.hard");
			}
			if (""!=temp) {
				document.getElementById("tiptext1").value = this.strings.getString("difficulty.label") + " " + temp + "(" + grid.get_rating() + ")";
			}
			temp = grid.get_best_time();
			if (""!=temp) {
				document.getElementById("tiptext2").value = this.strings.getString("besttime.label") + " " + temp;
			}
			temp = grid.get_avg_time();
			if (""!=temp) {
				document.getElementById("tiptext3").value = this.strings.getString("avgtime.label") + " " + temp;
			}
			if (grid.count>0) {
				if (1==grid.count) {
					document.getElementById("tiptext4").value = this.strings.getString("wincount1.label");
				} else {
					document.getElementById("tiptext4").value = this.strings.getFormattedString("wincount.label", ["" + grid.count], 1);
				}
				temp = grid.get_date();
				if (""!=temp) {
					document.getElementById("tiptext5").value = this.strings.getFormattedString("lastwin.label", [temp], 1);
				}
			}
		} catch (e) { /*not exactly good practise*/
		}

		return true;
	},
	_sentinel_0: 0
};

var gridsb = {
init: function() {
	// called when the sidebar is displayed
	treeView.init();
},
unload: function() {
	// called when the sidebar is hidden
},
_sentinel_0: 0
};

